home *** CD-ROM | disk | FTP | other *** search
- Path: EU.net!sun4nl!ittpub!ittpub!nntp
- Newsgroups: comp.lang.c++
- Subject: Re: Lifetime of temporary parameter objects
- Message-ID: <1996Mar14.131613.1805@ittpub>
- From: wil@ittpub.nl (Wil Evers)
- Date: 14 Mar 96 13:16:13 WET
- References: <4i6607$l4q@damon.irf.uni-dortmund.de>
- Distribution: world
- Nntp-Posting-Host: lintilla
-
- In article <4i6607$l4q@damon.irf.uni-dortmund.de>
- rothert@damon.irf.uni-dortmund.de (Bernd Rothert) writes:
-
- > I need some advice concerning the lifetime of temporary parameter
- > objects infunction calls:
- >
- > It is obviously correct to pass a reference to a temporary object to a
- > function - the compiler ensures that the temporary stays alive as long
- > as the reference exists (actual parameter of "const Stars&").
- >
- > What if passing a pointer to the CONTENTS of an explicitly constructed
- > temporary:
- >
- > ---
- > #include <string.h>
- > #include <iostream.h>
- > class Stars {
- > public:
- > Stars(int n) : _s(new char[n+1]) {
- > memset(_s, '*', n);
- > _s[n] = '\0';
- > }
- > ~Stars() {
- > delete _s;
- ^--- that should be delete[] _s;
- > _s = 0;
- > }
- > const char* get() const { return _s; }
- > private:
- > char* _s;
- > };
- > void banner(const Stars& st, const char* s) {
- > //=============
- > cout << st.get() << endl << s << endl;
- > }
- > int main() {
- > banner(40, Stars(40).get());
- > //===============
- > return 0;
- > }
- > ---
- >
- > The program passes a pointer to the "_s" member of a "Stars" object
- > to the "banner" function. This works for every compiler I have seen but
- > I don't know if I can rely on this behaviour and prefer defining an
- > auxiliary variable which is guaranteed to live until the function call
- > returns.
- >
- > Can anyone give me a hint?
-
- The older rules as defined in the ARM (1990) allowed the temporary Stars
- object created in `Stars(40).get()' to be destroyed *before* control was
- passed to banner(). Older versions of GNU C++ are known to do this. The
- draft ANSI/ISO standard effectively says the temporary will be destructed
- at the end of the statement, that is, after the call to banner(). But note
- that even the new rules may surprise us:
-
- void f()
- {
- char *p = Stars(40).get();
- cout << p << endl; // has undefined result
- }
-
- So if you have a class that passes a pointer to some data in its internal
- representation, I would always recommend using an explictly named
- variable.
-
- Hope this helps,
-
- - Wil
-